package com.api.controller;

import com.api.mapper.BuildingMapper;
import com.api.mapper.ChamberMapper;
import com.api.pojo.Chamber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chamber")
public class ChamberController {

    @Autowired
    ChamberMapper cm;

    @Autowired
    BuildingMapper bm;

    @PostMapping("/create")
    public Map<String, Object> create(Integer bid, String label) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        cm.create(bid, label);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @DeleteMapping("/remove")
    public Map<String, Object> remove(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        cm.remove(id);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @PutMapping("/update")
    public Map<String, Object> update(Integer id, Integer bid, String label) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        cm.update(id, bid, label);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @GetMapping("/get")
    public Map<String, Object> get(Integer bid, Integer pageNo, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        pageNo = --pageNo * pageSize;
        List<Chamber> list = bid == null ? cm.get(pageNo, pageSize) : cm.getByBid(bid, pageNo, pageSize);
        list.forEach(e -> {
            e.setBuilding(bm.getById(e.getBid()));
        });
        map.put("data", list);
        map.put("total", bid == null ? cm.count() : cm.countByBid(bid));
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @GetMapping("/getAll")
    public Map<String, Object> getAll(Integer bid) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        List<Chamber> list = cm.getAll(bid);
        map.put("data", list);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
